import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:intl/intl.dart';

// import 'package:launch_review/launch_review.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/index_setting.dart';
import 'package:flutter_syt/datas/message_model.dart';
import 'package:flutter_syt/datas/provider_index_setting.dart';
import 'package:flutter_syt/datas/station_item.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/message/message_sub_list.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:provider/provider.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import 'global_easy_loading.dart';
import 'root_widget.dart';

class GlobalData extends ChangeNotifier {
  static int countDownTime = 1656244800000;

  /// 回调监听使用
  static var data = GlobalData();

  /// 用于多层页面返回时返回于指定页面，返回后清空
  static String pageFrom = '';

  /// 登录后需要验证使用
  static var loaginCallback = false;

  static cleanPage() {
    pageFrom = '';
    data.notifyListeners();
  }

  /// 设置极光注册ID；
  static setRegistrationID(String registrationID) {
    print('registrationID ----> $registrationID');
    appContext.storage.setString("registrationID", registrationID);
  }

  /// 设置厂商推送token；
  static setDevicTokenID(String devicTokenID) {
    print('devicTokenID ----> $devicTokenID');
    appContext.storage.setString("devicTokenID", devicTokenID);
  }

  /// 绑定极光别名
  static bindPush() async {
    var registrationID = appContext.storage.getString("registrationID");
    if (registrationID != null && registrationID.isNotEmpty) {
      var platform = 5; //平台id 1:华为，2:小米，3:vivo，4:oppo，5:其它
      await API.shared.notificationBind.bind(registrationID, platform);
      // print('bindPush --- registrationID ----> $registrationID ------> platForm : $platform');
    }

    var devicTokenID = appContext.storage.getString("devicTokenID");
    if (registrationID != null && registrationID.isNotEmpty) {
      var platform = 5; //平台id 1:华为，2:小米，3:vivo，4:oppo，5:其它

      try {
        if (Platform.isAndroid) {

          var deviceData = appContext.andriodInfo; ;
          DLog('deviceData. manufacturer  ${deviceData.manufacturer}');
          if (deviceData.manufacturer.toLowerCase() == 'huawei') {
            platform = 1;
          } else if (deviceData.manufacturer.toLowerCase() == 'xiaomi') {
            platform = 2;
          } else if (deviceData.manufacturer.toLowerCase() == 'vivo') {
            platform = 3;
          } else if (deviceData.manufacturer.toLowerCase() == 'oppo' ||
              deviceData.manufacturer.toLowerCase() == 'oneplus') {
            platform = 4;
          }
        }
      } catch (e) {}
      if (platform != 5) {
        API.shared.notificationBind.bind(devicTokenID ?? '', platform);
      }

      // print('bindPush --- registrationID ----> $registrationID ------> platForm : $platform');
    }
  }

  static Future getIndexSetting() async {
    //  if (me.serial_number > 0) {
    IndexSetting setting = await API.shared.common.indexSetting();
    ProviderIndexSetting indexSettingProvider =
        Provider.of<ProviderIndexSetting>(appContext.context!, listen: false);
    // setting.service = 1;
    indexSettingProvider.indexSetting = setting;
    // });
    // }
  }

  /// 删除绑定别名
  static unbindPush() {
    var registrationID = appContext.storage.getString("registrationID");
    if (registrationID != null) {
      API.shared.notificationBind.del(registrationID);
      print('unbindJPush --- registrationID ----> $registrationID');
    }
  }

  static String privacyOverviewUrl(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).privacySmmaryUrl;
    return url;
  }

  static String privacyJuvenile(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).privacyJuvenile;
    return url;
  }

// sharingUrl

  static String sharingUrl(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).sharingUrl;
    return url;
  }

  static String collectionUrl(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).collectionUrl;
    return url;
  }

  static String privacyUrl(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).privacyUrl;
    return url;
  }

  static String userAgreeUrl(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).userAgreeUrl;
    return url;
  }

  static String upgrade(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).upgrade;
    return url;
  }

  static String aboutme(BuildContext context) {
    var url = appContext.provider.articleUrl + S.of(context).aboutmeurl;
    return url;
  }

  static String noticedetail(BuildContext context, int id) {
    var url =
        appContext.provider.articleUrl + S.of(context).noticedetail + '&id=$id';
    return url;
  }

  static String mallMine() {
    var url = appContext.provider.userMallUrl;
    var storyLocal = appContext.storage.getString("storyLocal");
    if (storyLocal != null) {
      url = url + "?lang=$storyLocal";
    } else {
      var local = Intl.getCurrentLocale();
      url = url + "?lang=$local";
    }
    return url;
  }

  static String mallGoodsInfoMine(GoodsInfoContentModel model) {
    var url = appContext.provider.userMallUrl;
    var storyLocal =
        appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale();
    if (model.type == '2') {
      url = url + "/mall/integral/${model.id}?lang=$storyLocal";
    } else {
      url = url + "/mall/goodsDetail/?g_id=${model.id}&lang=$storyLocal";
    }
    // if (storyLocal != null) {
    //   url = url + "?lang=$storyLocal";
    // } else {
    //   var local = Intl.getCurrentLocale();
    //   url = url + "?lang=$local";
    // }
    return url;
  }

  static String userPointUrl() {
    var url = appContext.provider.userPointUrl;
    var storyLocal = appContext.storage.getString("storyLocal");
    if (storyLocal != null) {
      url = url + "?lang=$storyLocal";
    } else {
      var local = Intl.getCurrentLocale();
      url = url + "?lang=$local";
    }
    return url;
  }

  static String activityMine() {
    // https://dev.mall.zhuoxinyoupin.com/mall/myactivity
    var url = appContext.provider.userMallUrl + "/mall/myactivity";
    var storyLocal = appContext.storage.getString("storyLocal");
    if (storyLocal != null) {
      url = url + "?lang=$storyLocal";
    } else {
      var local = Intl.getCurrentLocale();
      url = url + "?lang=$local";
    }
    return url;
  }
}

class JPushJump {
  static Map<int, dynamic> localMap = Map();

  /// 跳转目标（1:新闻详情，2:H5页面，3:赛事详情，4:消息）
  static excutePush(Map<String, dynamic> data) async {
    var url = "${data['url']}";
    var target = "${data['jump_target']}";
    final ctx = navigatorKey.currentContext;

    if (target == '1' && ctx != null) {
      RouteManager.push(ctx, url);
    } else if (target == '2' && ctx != null) {
      RouteManager.push(ctx, RoutMapping.webDetail(url));
    } else if (target == '3' && ctx != null) {
      RouteManager.push(ctx, RoutMapping.gameDetail(url, isVideo: false));
    } else if (target == '4' && ctx != null) {
      final entity = StationItem({});
      entity.pushlish_user_id = url;
      Navigator.of(ctx)
          .push(MaterialPageRoute(builder: (ctx) => MessageSubList(entity)));
    } else if (target == '5' && ctx != null) {
      if (!UserInfo.me.isLogin) {
        RouteManager.push(
          ctx,
          RoutMapping.loginByPwd(),
        );
        return;
      }
      RouteManager.push(
        ctx,
        RoutMapping.feedbackPage(1),
      );
    } else if (target == '6' && ctx != null) {
      RouteManager.push(ctx, RoutMapping.service_socket(url));
    }

    // else if (target == '6' && ctx != null) {
    //   RouteManager.push(ctx, RoutMapping.message());
    // }
  }
}

class VersionUpdate {
  static _doJump(String url) async {
    // LaunchReview.launch(iOSAppId: '1601140897', writeReview: false);

    // if (!await launch('$url', forceSafariVC: false, forceWebView: false)) {
    // throw '无法打开链接"$url"';
    // }
  }

  /// 版本更新
  static update(BuildContext context, bool needToast) async {
    var result = await API.shared.common.appUpdate();
    var build = 0;
    try {
      build = int.parse(result["build_version"] as String);
    } catch (e) {}

    var url = "${result['download_url']}";
    // 版本为空时过滤  下载链接为空时过滤
    if (build == 0 || url == 'null' || url.isEmpty) {
      return;
    }
    var localBuild = int.parse(appContext.packageInfo.buildNumber);
    var update = false;
    if (build > localBuild) {
      update = true;
    }
    // force_message
    bool isForceUpdate = result['is_force_update'] == 1;
    // update = true;
    // isForceUpdate = true;
    var message = isForceUpdate ? result['force_message'] : result['message'];
    if (update) {
      Future.delayed(Duration.zero, () {
        showCommonDialog(
            context,
            DialogEntity(S.of(context).upgrade_reminder, Text(message ?? ''),
                () => Navigator.of(context).pop(), () => {_doJump(url)},
                cancelText: S.of(context).cancel,
                okText: S.of(context).go_update,
                disableAndriodPop: true),
            hideCanel: isForceUpdate);
      });
    } else if (needToast) {
      customShowToast(S.of(context).local_news_version);
    }
  }
}
